import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Radio, Select, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { parentsList, getTeacher, sendMessage, msgList } from '@/services/api';
import { PAGE, SIZE, ALL } from '@/utils/constant';

interface props {
  onClosed: () => void;
  msgType: any;
  dispatch: (type: any) => void;
}

interface UserFormProps extends FormComponentProps {
  msgTypeData: any;
  ref: any;
}

const ref: any = React.createRef();
const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(({ form: { getFieldDecorator }, msgTypeData }: any) => {
  const [msgType, setMsgType] = useState(2);
  const [parentsData, setParentsData] = useState([]);
  const [teracherIdData, setTeracherIdData] = useState([]);

  const formItemLayout = {
    labelCol: {
      xs: { span: 4, offset: 4 },
    },
    wrapperCol: {
      sm: { span: 8 },
    },
  };

  //请求教师数据
  useEffect(() => {
    getTeacher({ page: PAGE, size: ALL }).then((resp: any) => {
      if (resp.status === 'success') {
        setTeracherIdData(resp.data.data);
      }
    });
    parentsList({ page: PAGE, size: SIZE }).then((resp: any) => {
      if (resp.status === 'success') {
        setParentsData(resp.data.data);
      }
    });
  }, []);
  return (
    <Form layout="horizontal" {...formItemLayout}>
      <Item label="发送人">
        {getFieldDecorator('sender_id', {
          rules: [
            {
              required: true,
              message: '必填',
            },
          ],
        })(
          <Select
            placeholder="请选择"
            allowClear
            showSearch
            defaultActiveFirstOption={false}
            filterOption={true}
            optionFilterProp="children"
            // onSearch={value => {
            //   if (value) {
            //     const searchValue = value.trim();
            //     getTeacher({ page: PAGE, size: ALL, keyword: searchValue }).then((resp: any) => {
            //       if (resp.status === 'success') {
            //         setParentsData(resp.data.data);
            //       }
            //     });
            //   }
            // }}
          >
            {teracherIdData.map((item: any) => (
              <Select.Option value={item.id} key={item.id}>
                {item.name}
              </Select.Option>
            ))}
          </Select>,
        )}
      </Item>
      <Item label="消息">
        {getFieldDecorator('receive_type', {
          initialValue: 2,
        })(
          <Radio.Group
            onChange={(e: any) => {
              setMsgType(e.target.value);
            }}
          >
            <Radio value={2}>系统消息</Radio>
            <Radio value={1}>个人消息</Radio>
          </Radio.Group>,
        )}
      </Item>
      {msgType === 1 && (
        <Item label="接收家长">
          {getFieldDecorator('receiver_id', {
            rules: [
              {
                required: true,
                message: '必填',
              },
            ],
          })(
            <Select
              placeholder="请选择"
              allowClear
              showSearch
              defaultActiveFirstOption={false}
              filterOption={false}
              onSearch={value => {
                if (value) {
                  const searchValue = value.trim();
                  parentsList({ page: PAGE, size: ALL, keyword: searchValue }).then((resp: any) => {
                    if (resp.status === 'success') {
                      setParentsData(resp.data.data);
                    }
                  });
                }
              }}
            >
              {parentsData.map((item: any) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Item>
      )}
      <Item label="消息类型">
        {getFieldDecorator('message_type_id', {
          rules: [
            {
              required: true,
              message: '必填',
            },
          ],
        })(
          <Select placeholder="请选择">
            {msgTypeData.map((v: any) => (
              <Select.Option value={v.id} key={v.id}>
                {v.title}
              </Select.Option>
            ))}
          </Select>,
        )}
      </Item>
      <Item label="标题">
        {getFieldDecorator('title', {
          rules: [
            {
              required: true,
              message: '必填',
            },
          ],
        })(<Input placeholder="请输入" />)}
      </Item>
      <Item label="内容">
        {getFieldDecorator('content', {
          rules: [
            {
              required: true,
              message: '必填',
            },
          ],
        })(<Input.TextArea placeholder="请输入" autoSize={{ minRows: 4 }} />)}
      </Item>
    </Form>
  );
});

const MyModal = ({ onClosed, msgType, dispatch }: props) => {
  return (
    <Modal
      onCancel={onClosed}
      visible
      title="新增消息"
      width="60%"
      maskClosable={false}
      onOk={() => {
        ref.current.validateFields((err: any, val: any) => {
          const newVal = JSON.parse(JSON.stringify(val));
          if (!err) {
            sendMessage(newVal).then((resp: any) => {
              if (resp.status === 'success') {
                notification.success({
                  message: '发送成功',
                });
                onClosed();
                dispatch({
                  type: 'OPEN_LOADING',
                });
                msgList({ page: PAGE, size: SIZE }).then((res: any) => {
                  if (res.status === 'success') {
                    dispatch({
                      type: 'GET_DATA',
                      payload: res.data.data,
                    });
                    dispatch({
                      type: 'CHANGE_PAGINATION',
                      payload: {
                        current: PAGE,
                        pageSize: SIZE,
                        showSizeChanger: true,
                        total: res.data.meta.total,
                      },
                    });
                  }
                  dispatch({
                    type: 'CLOSED_LOADING',
                  });
                });
              }
            });
          }
        });
      }}
    >
      <MyForm msgTypeData={msgType} ref={ref} />
    </Modal>
  );
};

export default MyModal;
